package com.liuning.redis.controller;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.liuning.redis.pojo.User;
import com.liuning.redis.utils.RedisUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.data.redis.connection.RedisConnection;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

/**
 * 测试RedisTemplate
 */
@RestController
public class RedisController {

    /**
     * 使用自己定义的redisTemplate
     */
    @Autowired
    @Qualifier("redisTemplate")
    private RedisTemplate redisTemplate;

    @Autowired
    private RedisUtil redisUtil;

    @RequestMapping("/redis")
    public void testRedis() {

        /**
         * opsForValue：操作字符串 类型String
         * opsForList:操作List
         * ......
         * 除了基本的操作，我们常用的方法都可以通过redisTemplate进行操作，比如事务和CRUD操作
         * 获取redis的连接对象：
         * redisTemplate.getConnectionFactory().getConnection();
         */
        // RedisConnection connection = redisTemplate.getConnectionFactory().getConnection();
        // connection.flushDb();
        // connection.flushAll();

        redisTemplate.opsForValue().set("myKey","南瓜");

        System.out.println("redis:" + redisTemplate.opsForValue().get("myKey"));
    }

    @RequestMapping("/redis2")
    public void testRedisConfig() throws JsonProcessingException {
        User user = new User("南瓜pumpkin", 20);
        String jsonUser = new ObjectMapper().writeValueAsString(user);
        redisTemplate.opsForValue().set("user",user);
        System.out.println("redis2:" + redisTemplate.opsForValue().get("user"));

    }

    @RequestMapping("/redis3")
        public String testRedisUtil() throws JsonProcessingException {

        redisUtil.set("name","hello world！");
        return (String) redisUtil.get("name");
    }
}
